package com.test.sdk.redis.controller;

import com.test.sdk.common.util.ErrorCodeTO;
import com.test.sdk.common.util.ResponseTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 徒有琴
 */
@RestController
public class RedisController {
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/set")
    public ResponseTO set(String key, String value) {
        try {
            redisTemplate.opsForValue().set(key, value);
        } catch (Exception e) {
            e.printStackTrace();
            //封装异常信息
            return ResponseTO.getErrorResult(new ErrorCodeTO("0000", e.getMessage()));
        }
        return ResponseTO.getOkResult("成功");
    }

    @RequestMapping("/setex")
    public ResponseTO setex(String key, String value, Integer expire) {
        try {
            redisTemplate.opsForValue().set(key, value, expire, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
            //封装异常信息
            return ResponseTO.getErrorResult(new ErrorCodeTO("0000", e.getMessage()));
        }
        return ResponseTO.getOkResult("成功");
    }
    @RequestMapping("/expire")
    public ResponseTO expire(String key, Integer expire) {
        try {
            redisTemplate.expire(key,expire,TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
            //封装异常信息
            return ResponseTO.getErrorResult(new ErrorCodeTO("0000", e.getMessage()));
        }
        return ResponseTO.getOkResult("成功");
    }


    @RequestMapping("/get")
    public ResponseTO get(String key) {
        Object value = redisTemplate.opsForValue().get(key);
        return ResponseTO.getOkResult(value);
    }

    @RequestMapping("/mset")
    public ResponseTO mset(@RequestBody Map param) {
        System.out.println(param);
        return ResponseTO.getOkResult("");
    }
}
